<template>
  <div>
    <el-button type="text" @click="changeComplain">投诉</el-button>
    <el-dialog title="投诉" :visible.sync="isComplain" width="30%" center>
      <el-row>
        <el-form
          ref="complainForm"
          :model="complainForm"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="投诉资讯">
            <el-input v-model="news.title" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="投诉内容" prop="content">
            <el-input
              v-model="complainForm.content"
              type="textarea"
              placeholder="请输入投诉原因"
              maxlength="300"
              show-word-limit
            ></el-input>
          </el-form-item>
        </el-form>
      </el-row>
      <el-row slot="footer" class="dialog-footer">
        <el-button @click="changeComplain">取 消</el-button>
        <el-button type="primary" @click="complain('complainForm')">
          确 定
        </el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: {
    news: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      isComplain: false,
      complainForm: {
        id: this.news.id,
        content: ''
      },
      rules: {
        content: [
          { required: true, message: '请输入投诉原因', trigger: 'blur' },
          {
            min: 10,
            max: 300,
            message: '长度在 10 到 300 个字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    changeComplain() {
      if (this.isComplain) {
        this.isComplain = false
        return
      }
      if (!this.$store.state.user.hasUser) {
        this.$message({
          message: '请先登录',
          type: 'warning'
        })
        return
      }
      this.isComplain = true
    },
    complain(formName) {
      const self = this
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const { status, data } = await self.$axios.post(
            '/news/complain',
            self.complainForm
          )
          if (status === 200) {
            if (data.code === 0) {
              self.$message({
                message: '投诉成功',
                type: 'success'
              })
            } else {
              self.$message({
                message: data.msg,
                type: 'error'
              })
            }
          }
        } else {
          self.$message({
            message: '请先填写投诉原因',
            type: 'error'
          })
          return false
        }
      })
      this.changeComplain()
    }
  }
}
</script>

<style></style>
